<?php

$ws = new swoole_websocket_server("0.0.0.0", 9501);
$ws->on("open", function($ws, $request) {
    echo '新用户加入', $request->fd, PHP_EOL;
    $GLOBALS['fd'][$request->fd]['id'] = $request->fd;
    $GLOBALS['fd'][$request->fd]['name'] = '匿名用户' . $request->fd;
    // $ws->push($request->fd, "welcome\n");
});
$ws->on("message", function($ws, $request) {
    // echo "message: $request->data";
    $msg = $GLOBALS['fd'][$request->fd]['name'] . ":" . $request->data . PHP_EOL;
    if (strstr($request->data, "#name#")) {
        $GLOBALS['fd'][$request->fd]['name'] = str_replace("#name#", '', $request->data);
    } else {
        foreach ($GLOBALS['fd'] as $fd) {
            $ws->push($fd['id'], $msg);
        }
    }
    // $ws->push($request->fd, "get message");
});
$ws->on("close", function($ws, $request) {
    echo "{$GLOBALS['fd'][$request->fd]['name']}退出房间" . PHP_EOL;
    unset($GLOBALS['fd'][$request->fd]);
});
$ws->start();